<template>
  <div class="shop-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="container">
        <div class="header-content">
          <div class="logo">
            <h1>旅行商城</h1>
          </div>
          <!-- 修改后的顶部导航栏 -->
          <nav class="nav">
            <ul>
              <li><a href="#" class="nav-link" @click.prevent="scrollToCategory(1)">景点门票</a></li>
              <li><a href="#" class="nav-link" @click.prevent="scrollToCategory(2)">酒店预订</a></li>
              <li><a href="#" class="nav-link" @click.prevent="scrollToCategory(3)">旅游套餐</a></li>
              <li><a href="#" class="nav-link" @click.prevent="scrollToCategory(4)">周边商品</a></li>
            </ul>
          </nav>
          <div class="user-actions">
            <!-- 新增首页按钮 -->
            <el-button type="primary" color="#90EE90" @click="goHome">返回首页</el-button>
<!--            <el-button type="text" @click="login">登录</el-button>-->
<!--            <el-button type="text" @click="register">注册</el-button>-->
          </div>
        </div>
      </div>
    </header>

    <!-- 搜索栏 -->
    <div class="search-container">
      <el-search
          v-model:query="searchKey"
          placeholder="搜索旅游套餐/景点门票"
          @search="fetchFilteredProducts"
          class="search-bar"
      />
    </div>

    <!-- 轮播图 -->
    <div class="banner-container">
      <el-carousel height="400px" effect="fade">
        <el-carousel-item v-for="(banner, index) in banners" :key="index">
          <img :src="banner.imageUrl" alt="轮播图" class="banner-img">
          <div class="banner-info">
            <h3>{{ banner.title }}</h3>
            <p>{{ banner.description }}</p>
            <el-button type="primary" @click="goToBannerDetail(banner.link)">立即查看</el-button>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 热门推荐 -->
    <div class="hot-recommend">
      <h2 class="section-title">热门推荐</h2>
      <el-row :gutter="20">
        <el-col :span="6" v-for="product in hotProducts" :key="product.id">
          <el-card class="hot-product-card">
            <div class="product-image-container">
              <img :src="product.imageUrl" alt="商品图" class="hot-product-img">
              <div class="discount-badge" v-if="product.discount">
                {{ product.discount * 10 }}折
              </div>
            </div>
            <div class="hot-product-info">
              <h3 class="hot-product-title">{{ product.title }}</h3>
              <div class="hot-product-price">
                <span class="current-price">￥{{ product.price }}</span>
                <span class="original-price" v-if="product.originalPrice">￥{{ product.originalPrice }}</span>
              </div>
              <el-button type="info" size="small" @click="goToProductDetail(product.id)" class="mt-2">
                查看详情
              </el-button>
              <el-button type="primary" size="small" @click="addToCart(product)">
                加入购物车
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 修改后的商品分类展示区（已删除大图标） -->
    <div class="category-container">
      <h2 class="section-title">商品分类</h2>
      <el-row :gutter="20">
        <el-col :span="24" v-for="category in categories" :key="category.id">
          <div class="category-block" :id="'category-'+category.id">
            <h3 class="category-name">{{ category.name }}</h3>
            <el-row :gutter="20">
              <el-col :span="6" v-for="product in getProductsByCategory(category.id)" :key="product.id">
                <el-card class="product-card">
                  <img :src="product.imageUrl" alt="商品图" class="product-img" />
                  <div class="product-info">
                    <h4 class="product-title">{{ product.title }}</h4>
                    <div class="product-description" v-if="product.description">
                      {{ product.description }}
                    </div>
                    <el-button
                        type="info"
                        size="small"
                        @click="goToProductDetail(product.id)"
                        class="mt-2"
                    >
                      查看详情
                    </el-button>
                    <div class="product-price">￥{{ product.price }}</div>
                    <el-button
                        type="primary"
                        size="small"
                        @click="addToCart(product)"
                        class="mt-2"
                    >
                      加入购物车
                    </el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 购物车侧边栏（可缩放） -->
    <div
        v-if="isCartVisible || isCartMinimized"
        :class="{
        'cart-sidebar': true,
        'cart-slide-in': isCartVisible,
        'cart-minimized': isCartMinimized
      }"
    >
      <div class="cart-header" v-if="isCartVisible">
        <h3>购物车</h3>
        <div class="cart-controls">
          <!-- 最小化按钮 -->
          <button class="minimize-btn" @click="minimizeCart">
            最小化
          </button>
          <!-- 关闭按钮 -->
          <button class="close-btn" @click="toggleCart">
            <i class="fa fa-times"></i>
          </button>
        </div>
      </div>

      <!-- 完整购物车内容（展开状态） -->
      <div class="cart-content" v-if="isCartVisible">
        <div class="cart-items" v-if="cart.length > 0">
          <el-scrollbar>
            <div class="cart-item" v-for="item in cart" :key="item.id">
              <div class="item-content">
                <img :src="item.imageUrl" alt="商品缩略图" class="item-image" />
                <div class="item-info">
                  <h4 class="item-title">{{ item.title }}</h4>
                  <div class="item-price">￥{{ item.price }}</div>
                  <div class="item-quantity">
                    <button @click="decreaseQuantity(item.id)" class="quantity-btn">-</button>
                    <span>{{ item.quantity || 1 }}</span>
                    <button @click="increaseQuantity(item.id)" class="quantity-btn">+</button>
                  </div>
                </div>
              </div>
              <button class="remove-btn" @click="removeFromCart(item.id)">
                <i class="fa fa-trash"></i>
              </button>
            </div>
          </el-scrollbar>
        </div>

        <div class="cart-empty" v-else>
          <i class="fa fa-shopping-cart"></i>
          <p>购物车是空的</p>
        </div>
      </div>

      <!-- 结算按钮始终固定在底部 -->
      <div class="cart-footer-fixed" v-if="isCartVisible && cart.length > 0">
        <div class="total-price">
          <span>总价:</span>
          <span class="price-value">￥{{ getTotalPrice }}</span>
        </div>
        <el-button type="primary" @click="showPaymentOptionsAndGenerateOrder">结算</el-button>
        <!-- 新增生成订单按钮 -->
        <el-button type="success" @click="generateOrder">生成订单</el-button>
      </div>

      <!-- 最小化购物车内容（简化显示） -->
      <div class="cart-minimized-content" v-if="isCartMinimized">
        <button class="restore-btn" @click="restoreCart">
          <i class="fa fa-expand"></i>
        </button>
        <span class="minimized-count">购物车 ({{ cartCount }})</span>
      </div>
    </div>

    <!-- 支付方式选择区域 -->
    <div v-if="showPaymentModal" class="payment-modal">
      <div class="payment-modal-content">
        <h3>请选择支付方式</h3>
        <div class="payment-buttons">
          <el-button type="primary" @click="processPayment('alipay')">
            <i class="fa fa-credit-card"></i> 支付宝支付
          </el-button>
          <el-button type="success" @click="processPayment('wechat')">
            <i class="fa fa-wechat"></i> 微信支付
          </el-button>
          <el-button type="info" @click="processPayment('creditCard')">
            <i class="fa fa-credit-card-alt"></i> 信用卡支付
          </el-button>
        </div>
        <el-button type="default" @click="cancelPayment">取消</el-button>
      </div>
    </div>

    <!-- 页脚 -->
    <footer class="footer">
      <div class="container">
        <div class="footer-content">
          <div class="footer-section">
            <h4>关于我们</h4>
            <p>我们是一家专注于旅游服务的公司，提供景点门票、酒店预订、旅游套餐等服务。</p>
          </div>
          <div class="footer-section">
            <h4>联系我们</h4>
            <p>电话：400-123-4567</p>
            <p>邮箱：contact@travelshop.com</p>
          </div>
          <div class="footer-section">
            <h4>关注我们</h4>
            <div class="social-links">
              <a href="#" class="social-link"><i class="fa fa-weibo"></i></a>
              <a href="#" class="social-link"><i class="fa fa-wechat"></i></a>
              <a href="#" class="social-link"><i class="fa fa-instagram"></i></a>
              <a href="#" class="social-link"><i class="fa fa-twitter"></i></a>
            </div>
          </div>
        </div>
        <div class="copyright">
          <p>&copy; © 2025 G.T.I Security Organization All rights reserved.</p>
        </div>
      </div>
    </footer>
  </div>

  <el-backtop :right="40" :bottom="80" :visibility-height="200" class="custom-backtop">
    <el-icon size="24"><ArrowUp /></el-icon>
  </el-backtop>
</template>

<script setup>
import { ref, computed} from 'vue';
import { useRouter } from 'vue-router';
import {
  Location,
  Hotel,
  MagicStick,
  Goods,
} from '@element-plus/icons-vue';

// 添加首页跳转方法
const goHome = () => {
  router.push('/') // 假设首页路由为'/'
}

const router = useRouter();

// 页面数据
const searchKey = ref('');
const banners = ref([
  {
    imageUrl: 'https://picsum.photos/seed/banner1/1200/400',
    title: '夏日特惠',
    description: '热门景点门票低至5折',
    link: '/promotion/summer'
  },
  {
    imageUrl: 'https://picsum.photos/seed/banner2/1200/400',
    title: '酒店预订',
    description: '预订酒店享受免费早餐',
    link: '/hotels'
  },
  {
    imageUrl: 'https://picsum.photos/seed/banner3/1200/400',
    title: '旅游套餐',
    description: '精选旅游套餐，一价全包',
    link: '/tours'
  }
]);
const categories = ref([
  { id: 1, name: '景点门票', icon: Location },
  { id: 2, name: '酒店预订', icon: Hotel },
  { id: 3, name: '旅游套餐', icon: MagicStick },
  { id: 4, name: '周边商品', icon: Goods },
]);
const productList = ref([]);
const hotProducts = ref([]);
const cart = ref([]);
const isCartVisible = ref(false);
const isCartMinimized = ref(false);
const showPaymentModal = ref(false);

// 初始化商品数据
const fetchProducts = async () => {
  try {
    productList.value = [
      {
        id: 1,
        title: '故宫门票',
        price: 60,
        originalPrice: 80,
        discount: 0.75,
        imageUrl: 'https://ts1.tc.mm.bing.net/th/id/OIP-C.hb4dYRpXgtZtA9Lp0TmUmgHaEz?w=240&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2',
        categoryId: 1,
        description: '故宫是中国明清两代的皇家宫殿，位于北京中轴线的中心，是中国古代宫廷建筑之精华。',
        gallery: [
          'https://picsum.photos/seed/ticket1-1/600/400',
          'https://picsum.photos/seed/ticket1-2/600/400',
          'https://picsum.photos/seed/ticket1-3/600/400'
        ],
        detailContent: '<p>故宫是中国明清两代的皇家宫殿，旧称紫禁城，位于北京中轴线的中心。故宫以三大殿为中心，占地面积72万平方米，建筑面积约15万平方米，有大小宫殿七十多座，房屋九千余间。</p><p>开放时间：08:30-17:00（旺季）</p><p>建议游玩时间：3-4小时</p>',
        params: {
          '景点类型': '历史建筑',
          '适合人群': '所有人群',
          '开放时间': '08:30-17:00',
          '建议游玩时间': '3-4小时'
        },
        reviews: [
          {
            id: 1,
            user: { name: '游客1', avatar: 'https://picsum.photos/seed/user1/40/40' },
            rating: 5,
            date: '2023-05-15',
            content: '非常震撼的古代建筑群，值得一去！',
            images: ['https://picsum.photos/seed/review1-1/200/200']
          }
        ],
        specs: [
          { id: 'adult', name: '成人票', price: 60 },
          { id: 'child', name: '儿童票', price: 30 },
          { id: 'senior', name: '老人票', price: 30 }
        ],
        stock: 100
      },
      {
        id: 2,
        title: '长城门票',
        price: 40,
        originalPrice: 50,
        discount: 0.8,
        imageUrl: 'https://ts1.tc.mm.bing.net/th/id/OIP-C.SQ6R8xfzpyOeqPkwCLG-pgHaE8?w=240&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2',
        categoryId: 1,
        description: '世界文化遗产，位于北京，被誉为"天下第一关"，是古代军事防御工程的杰出代表。',
        gallery: [
          'https://picsum.photos/seed/ticket2-1/600/400',
          'https://picsum.photos/seed/ticket2-2/600/400'
        ],
        detailContent: '<p>长城是中国古代的军事防御工程，是一道高大、坚固而连绵不断的长垣，用以限隔敌骑的行动。长城不是一道单纯孤立的城墙，而是以城墙为主体，同大量的城、障、亭、标相结合的防御体系。</p><p>开放时间：06:30-19:00</p><p>建议游玩时间：2-3小时</p>',
        params: {
          '景点类型': '历史遗迹',
          '适合人群': '所有人群',
          '开放时间': '06:30-19:00',
          '建议游玩时间': '2-3小时'
        },
        reviews: [
          {
            id: 1,
            user: { name: '游客2', avatar: 'https://picsum.photos/seed/user2/40/40' },
            rating: 4,
            date: '2023-06-10',
            content: '非常壮观，但爬上去有点累。',
            images: ['https://picsum.photos/seed/review2-1/200/200']
          }
        ],
        specs: [
          { id: 'adult', name: '成人票', price: 40 },
          { id: 'child', name: '儿童票', price: 20 }
        ],
        stock: 80
      },
      {
        id: 3,
        title: '颐和园门票',
        price: 30,
        imageUrl: 'https://ts1.tc.mm.bing.net/th/id/R-C.f239bbec543d8938dd9b7a82655df6af?rik=sOBEAMv8vf1gZA&riu=http%3a%2f%2fimg1.qunarzz.com%2ftravel%2fd0%2f1410%2f13%2f13a7db6954db429f213a9cdb.jpg_r_1024x683x95_81ba6e70.jpg&ehk=4dqLpkpy7rBYOej45mAcJlHv0wFeB%2bva85P9wLT8OFc%3d&risl=&pid=ImgRaw&r=0',
        categoryId: 1,
        description: '中国清朝时期皇家园林，前身为清漪园，坐落在北京西郊，与圆明园毗邻。',
        gallery: [
          'https://picsum.photos/seed/ticket3-1/600/400',
          'https://picsum.photos/seed/ticket3-2/600/400'
        ],
        detailContent: '<p>颐和园是保存最完整的一座皇家行宫御苑，被誉为"皇家园林博物馆"，也是国家重点文物保护单位。</p><p>开放时间：06:30-18:00</p><p>建议游玩时间：3-4小时</p>',
        params: {
          '景点类型': '皇家园林',
          '适合人群': '所有人群',
          '开放时间': '06:30-18:00',
          '建议游玩时间': '3-4小时'
        },
        reviews: [
          {
            id: 1,
            user: { name: '游客3', avatar: 'https://picsum.photos/seed/user3/40/40' },
            rating: 5,
            date: '2023-04-22',
            content: '湖光山色，非常美丽的地方。',
            images: ['https://picsum.photos/seed/review3-1/200/200']
          }
        ],
        specs: [
          { id: 'adult', name: '成人票', price: 30 },
          { id: 'child', name: '儿童票', price: 15 }
        ],
        stock: 120
      },
      {
        id: 4,
        title: '天坛公园门票',
        price: 15,
        imageUrl: 'https://ts1.tc.mm.bing.net/th/id/R-C.1b1688be7241d44ff375e728c4d040e3?rik=l%2bkJ9FTM6ssydw&riu=http%3a%2f%2fimg95.699pic.com%2fphoto%2f50020%2f5326.jpg_wh860.jpg&ehk=5rVmfq6XAV5G3wtZKmtVw00%2bCOoE2UZWZbT12Gv48HE%3d&risl=&pid=ImgRaw&r=0',
        categoryId: 1,
        description: '天坛是明清两朝帝王祭天、祈谷的场所，是现存中国古代规模最大、伦理等级最高的祭祀建筑群。',
        gallery: [
          'https://picsum.photos/seed/ticket4-1/600/400'
        ],
        detailContent: '<p>天坛公园在北京市南部，东城区永定门内大街东侧。占地约273万平方米。天坛始建于明永乐十八年(1420年)，清乾隆、光绪时曾重修改建。</p><p>开放时间：06:00-21:00</p><p>建议游玩时间：2-3小时</p>',
        params: {
          '景点类型': '历史建筑',
          '适合人群': '所有人群',
          '开放时间': '06:00-21:00',
          '建议游玩时间': '2-3小时'
        },
        reviews: [
          {
            id: 1,
            user: { name: '游客4', avatar: 'https://picsum.photos/seed/user4/40/40' },
            rating: 4,
            date: '2023-07-05',
            content: '建筑很有特色，公园环境很好。',
            images: ['https://picsum.photos/seed/review4-1/200/200']
          }
        ],
        specs: [
          { id: 'adult', name: '成人票', price: 15 },
          { id: 'child', name: '儿童票', price: 7.5 }
        ],
        stock: 200
      },
      // 酒店预订
      {
        id: 5,
        title: '快捷酒店',
        price: 200,
        originalPrice: 250,
        discount: 0.8,
        imageUrl: 'https://ts1.tc.mm.bing.net/th/id/OIP-C.aYH9Jm4Ti_vkZKrS3a_3wQHaE6?w=240&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2',
        categoryId: 2,
        description: '经济实惠的连锁酒店，提供舒适的住宿环境和优质的服务。',
        gallery: [
          'https://picsum.photos/seed/hotel1-1/600/400',
          'https://picsum.photos/seed/hotel1-2/600/400'
        ],
        detailContent: '<p>我们的快捷酒店位于市中心，交通便利，周边餐饮、购物设施齐全。房间干净整洁，提供免费WiFi和早餐。</p><p>入住时间：14:00</p><p>退房时间：12:00</p>',
        params: {
          '酒店类型': '经济型',
          '设施': '免费WiFi, 早餐, 24小时前台',
          '入住时间': '14:00',
          '退房时间': '12:00'
        },
        reviews: [
          {
            id: 1,
            user: { name: '游客5', avatar: 'https://picsum.photos/seed/user5/40/40' },
            rating: 3,
            date: '2023-06-15',
            content: '性价比高，基本需求都能满足。',
            images: ['https://picsum.photos/seed/review5-1/200/200']
          }
        ],
        specs: [
          { id: 'standard', name: '标准间', price: 200 },
          { id: 'deluxe', name: '豪华间', price: 280 }
        ],
        stock: 50
      },
      {
        id: 6,
        title: '隐世酒店',
        price: 1000,
        imageUrl: '',
        categoryId: 2,
        description: '高端精品酒店，提供私密、奢华的住宿体验。',
        gallery: [
          'https://picsum.photos/seed/hotel2-1/600/400',
          'https://picsum.photos/seed/hotel2-2/600/400',
          'https://picsum.photos/seed/hotel2-3/600/400'
        ],
        detailContent: '<p>隐世酒店位于风景优美的郊区，提供私人管家服务、高端餐饮和水疗设施。每个房间都经过精心设计，确保客人的隐私和舒适。</p><p>入住时间：15:00</p><p>退房时间：12:00</p>',
        params: {
          '酒店类型': '豪华型',
          '设施': '私人管家, 水疗中心, 高端餐饮',
          '入住时间': '15:00',
          '退房时间': '12:00'
        },
        reviews: [
          {
            id: 1,
            user: { name: '游客6', avatar: 'https://picsum.photos/seed/user6/40/40' },
            rating: 5,
            date: '2023-05-20',
            content: '绝对值得这个价格，服务无可挑剔！',
            images: ['https://picsum.photos/seed/review6-1/200/200']
          }
        ],
        specs: [
          { id: 'suite', name: '套房', price: 1000 },
          { id: 'villa', name: '别墅', price: 2500 }
        ],
        stock: 20
      },
      // 其他酒店和商品按照相同格式补充...
      // 旅游套餐
      {
        id: 10,
        title: '九寨沟三日游',
        price: 1299,
        originalPrice: 1599,
        discount: 0.81,
        imageUrl: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.iBJ2n0ND5lbXMT6pD62_UQHaE1?w=272&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7',
        categoryId: 3,
        description: '探索九寨沟的自然奇观，体验藏族文化，享受舒适的住宿和美食。',
        gallery: [
          'https://picsum.photos/seed/tour1-1/600/400',
          'https://picsum.photos/seed/tour1-2/600/400'
        ],
        detailContent: '<p>九寨沟三日游包含往返交通、两晚住宿、景区门票和导游服务。行程包括九寨沟核心景区游览、藏族村寨参观和特色餐饮体验。</p><p>出发日期：每周一、三、五</p>',
        params: {
          '行程天数': '3天2晚',
          '包含项目': '交通, 住宿, 门票, 导游',
          '出发日期': '每周一、三、五'
        },
        reviews: [
          {
            id: 1,
            user: { name: '游客10', avatar: 'https://picsum.photos/seed/user10/40/40' },
            rating: 4,
            date: '2023-07-01',
            content: '风景太美了，导游也很专业。',
            images: ['https://picsum.photos/seed/review10-1/200/200']
          }
        ],
        specs: [
          { id: 'standard', name: '标准套餐', price: 1299 },
          { id: 'deluxe', name: '豪华套餐', price: 1899 }
        ],
        stock: 30
      },
      // 周边商品
      {
        id: 13,
        title: '景区纪念钥匙链',
        price: 20,
        imageUrl: 'https://tse4-mm.cn.bing.net/th/id/OIP-C.iBUhXoRhZ_e32SE6EgzHsgHaFj?w=264&h=198&c=7&r=0&o=5&dpr=1.3&pid=1.7',
        categoryId: 4,
        description: '精美的景区纪念钥匙链，刻有景区标志性建筑图案。',
        gallery: [
          'https://picsum.photos/seed/good1-1/600/400',
          'https://picsum.photos/seed/good1-2/600/400'
        ],
        detailContent: '<p>景区纪念钥匙链采用优质金属材料制作，表面镀金处理，不易褪色。尺寸约5cm×3cm，重量约30g。</p><p>材质：合金</p><p>尺寸：5cm×3cm</p>',
        params: {
          '材质': '木制',
          '尺寸': '5cm×3cm',
          '重量': '30g'
        },
        reviews: [
          {
            id: 1,
            user: { name: '游客13', avatar: 'https://picsum.photos/seed/user13/40/40' },
            rating: 4,
            date: '2023-06-18',
            content: '做工精致，作为纪念品很不错。',
            images: ['https://picsum.photos/seed/review13-1/200/200']
          }
        ],
        specs: [
          { id: 'gold', name: '金色款', price: 20 },
          { id: 'silver', name: '银色款', price: 20 }
        ],
        stock: 150
      }
      // 其他商品按照相同格式补充...
    ];

    // 随机选择一些商品作为热门推荐
    hotProducts.value = [...productList.value]
        .sort(() => Math.random() - 0.5)
        .slice(0, 4);
  } catch (error) {
    console.error('获取商品数据失败:', error);
  }
};

// 根据分类筛选商品
const getProductsByCategory = (categoryId) => {
  return productList.value.filter((product) => product.categoryId === categoryId);
};

// 根据搜索关键词过滤商品
const fetchFilteredProducts = () => {
  if (searchKey.value === '') {
    fetchProducts();
  } else {
    const keyword = searchKey.value.toLowerCase();
    productList.value = productList.value.filter(product =>
        product.title.toLowerCase().includes(keyword)
    );
  }
};

// 添加商品到购物车
const addToCart = (product) => {
  const existingItemIndex = cart.value.findIndex((item) => item.id === product.id);
  if (existingItemIndex !== -1) {
    cart.value[existingItemIndex].quantity = (cart.value[existingItemIndex].quantity || 1) + 1;
  } else {
    cart.value.push({ ...product, quantity: 1 });
  }
  isCartVisible.value = true;
  isCartMinimized.value = false;

  // 添加弹跳动画效果
  const cartIndicator = document.querySelector('.cart-indicator, .cart-sidebar');
  if (cartIndicator) {
    cartIndicator.classList.add('bounce');
    setTimeout(() => cartIndicator?.classList.remove('bounce'), 500);
  }
};

// 从购物车移除商品
const removeFromCart = (id) => {
  cart.value = cart.value.filter((item) => item.id !== id);
};

// 增加商品数量
const increaseQuantity = (id) => {
  const item = cart.value.find((item) => item.id === id);
  if (item) item.quantity += 1;
};

// 减少商品数量
const decreaseQuantity = (id) => {
  const itemIndex = cart.value.findIndex((item) => item.id === id);
  if (itemIndex !== -1) {
    if (cart.value[itemIndex].quantity > 1) {
      cart.value[itemIndex].quantity -= 1;
    } else {
      cart.value.splice(itemIndex, 1);
    }
  }
};

// 计算总价
const getTotalPrice = computed(() =>
    cart.value.reduce((total, item) => total + (item.price * (item.quantity || 1)), 0)
);

// 计算商品总数
const cartCount = computed(() =>
    cart.value.reduce((total, item) => total + (item.quantity || 1), 0)
);

// 切换购物车显示/隐藏
const toggleCart = () => {
  isCartVisible.value = !isCartVisible.value;
  isCartMinimized.value = false;
};

// 最小化购物车
const minimizeCart = () => {
  isCartMinimized.value = true;
  isCartVisible.value = false;
};

// 恢复购物车
const restoreCart = () => {
  isCartMinimized.value = false;
  isCartVisible.value = true;
};

// 显示支付方式选择区域并生成订单
const showPaymentOptionsAndGenerateOrder = () => {
  if (cart.value.length > 0) {
    generateOrder();
    showPaymentModal.value = true;
  }
};

// 处理支付
const processPayment = (paymentMethod) => {
  console.log('正在使用', paymentMethod, '支付', getTotalPrice.value, '元');
  // 这里应该调用实际的支付API
  setTimeout(() => {
    cart.value = [];
    showPaymentModal.value = false;
    isCartVisible.value = false;
    isCartMinimized.value = false;
    alert('支付成功！');
  }, 500);
};

// 取消支付
const cancelPayment = () => {
  showPaymentModal.value = false;
};

// 跳转到商品详情页
const goToProductDetail = (productId) => {
  router.push({ name: 'ProductDetail', params: { id: productId } });
};

// 跳转到轮播图详情页
const goToBannerDetail = (link) => {
  router.push(link);
};

// 用户登录
const login = () => {
  alert('登录功能即将上线');
};

// 用户注册
const register = () => {
  alert('注册功能即将上线');
};
// 添加滚动到分类的方法
const scrollToCategory = (categoryId) => {
  const element = document.getElementById(`category-${categoryId}`);
  if (element) {
    // 使用平滑滚动效果
    element.scrollIntoView({
      behavior: 'smooth'
    });

    // 可选：为当前分类添加高亮效果
    const categories = document.querySelectorAll('.category-block');
    categories.forEach(cat => {
      cat.style.borderLeft = 'none';
    });
    element.style.borderLeft = '4px solid #409eff';
    element.style.paddingLeft = '16px';
    element.style.transition = 'all 0.3s ease';
  }
};

// 初始化数据
fetchProducts();
scrollToCategory();

// 生成订单
const generateOrder = () => {
  if (cart.value.length > 0) {
    const newOrder = {
      orderId: Date.now(), // 生成唯一订单号
      orderType: '商城购物单',
      createTime: new Date().toISOString(),
      totalAmount: getTotalPrice.value,
      status: '我发起的',
      review: { rating: 0, comment: '', submitted: false },
      items: cart.value.map(item => ({
        name: item.title,
        price: item.price,
        quantity: item.quantity || 1
      }))
    };

    // 保存订单到 localStorage
    const existingOrders = JSON.parse(localStorage.getItem('orders') || '[]');
    existingOrders.push(newOrder);
    localStorage.setItem('orders', JSON.stringify(existingOrders));

    // 清空购物车
    cart.value = [];
    isCartVisible.value = false;
    isCartMinimized.value = false;

    // 提示并跳转到 MyOrders 页面
    alert('订单已生成！');
    router.push('/my-orders');
  }
};
</script>

<style scoped>

.custom-backtop {
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.25);
  display: flex !important;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.user-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}
/* 通用样式 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  margin: 40px 0 20px;
  text-align: center;
}

/* 顶部导航栏样式 */
.header {
  background-color: #409eff;
  color: white;
  padding: 15px 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
}

.nav ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
}

.nav ul li {
  margin-right: 20px;
}

.nav-link {
  color: white;
  text-decoration: none;
  position: relative;
  transition: color 0.3s;
}

.nav-link::after {
  content: '';
  position: absolute;
  width: 0;
  height: 2px;
  bottom: -5px;
  left: 0;
  background-color: white;
  transition: width 0.3s ease-in-out;
}

.nav-link:hover {
  color: #e0e0e0;
}

.nav-link:hover::after {
  width: 100%;
}

.user-actions {
  display: flex;
  gap: 10px;
}
/* 添加分类高亮样式 */
.category-block {
  transition: all 0.3s ease;
  padding-left: 12px;
  border-left: 4px solid transparent;
}

/* 导航链接激活状态 */
.nav-link.active {
  color: #e0e0e0;
  font-weight: bold;
}

.nav-link.active::after {
  width: 100%;
}
/* 搜索栏样式 */
.search-container {
  padding: 20px 0;
  background-color: #f5f7fa;
}

/* 轮播图样式 */
.banner-container {
  position: relative;
}

.banner-img {
  width: 100%;
  height: 400px;
  object-fit: cover;
}

.banner-info {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 20px;
  border-radius: 4px;
}

.banner-info h3 {
  margin: 0;
}

.banner-info p {
  margin: 10px 0;
}

/* 热门推荐样式 */
.hot-product-card {
  height: 100%;
}

.product-image-container {
  position: relative;
}

.discount-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: #f56c6c;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.hot-product-img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.hot-product-info {
  padding: 10px;
}

.hot-product-title {
  margin: 0;
  font-size: 16px;
}

.hot-product-price {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 5px;
}

.current-price {
  font-weight: 600;
}

.original-price {
  text-decoration: line-through;
  color: #999;
}

/* 商品分类展示区样式 */
.category-block {
  margin-bottom: 40px;
}

.category-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.category-name {
  margin: 0;
  font-size: 20px;
}

.product-card {
  height: 100%;
}

.product-img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-info {
  padding: 10px;
}

.product-title {
  margin: 0;
  font-size: 16px;
}

.product-description {
  margin-top: 5px;
  font-size: 14px;
  color: #666;
}

.product-price {
  margin-top: 10px;
  font-weight: 600;
}

/* 购物车侧边栏样式 */
.cart-sidebar {
  position: fixed;
  top: 0;
  right: -300px;
  width: 300px;
  height: 100vh;
  background-color: white;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
  transition: right 0.3s;
  z-index: 1000;
}

.cart-slide-in {
  right: 0;
}

.cart-minimized {
  right: -260px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.cart-controls {
  display: flex;
  gap: 10px;
}

.minimize-btn,
.close-btn,
.restore-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
}

.cart-content {
  height: calc(100% - 100px);
  overflow-y: auto;
  padding: 15px;
}

.cart-items {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 10px;
}

.item-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.item-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.item-info {
  display: flex;
  flex-direction: column;
}

.item-title {
  margin: 0;
  font-size: 14px;
}

.item-price {
  font-size: 14px;
}

.item-quantity {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-top: 5px;
}

.quantity-btn {
  background: none;
  border: 1px solid #e0e0e0;
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 4px;
}

.remove-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: #f56c6c;
  font-size: 16px;
}

.cart-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.cart-footer-fixed {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background-color: white;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-price {
  display: flex;
  align-items: center;
  gap: 10px;
}

.price-value {
  font-weight: 600;
}

.cart-minimized-content {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  background-color: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.minimized-count {
  font-size: 14px;
}

/* 支付方式选择区域样式 */
.payment-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1001;
}

.payment-modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.payment-buttons {
  display: flex;
  gap: 20px;
}

/* 页脚样式 */
.footer {
  background-color: #f5f7fa;
  padding: 40px 0;
  margin-top: 40px;
}

.footer-content {
  display: flex;
  justify-content: space-between;
  gap: 40px;
}

.footer-section {
  flex: 1;
}

.footer-section h4 {
  margin: 0;
  margin-bottom: 10px;
}

.social-links {
  display: flex;
  gap: 10px;
}

.social-link {
  color: #666;
  font-size: 20px;
}

.copyright {
  margin-top: 20px;
  text-align: center;
  color: #999;
}

/* 弹跳动画 */
@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

.bounce {
  animation: bounce 0.5s;
}
</style>

